#include "BilinearInterpolator.h"
#include "Color.h"
#include <cmath>
#include "ReadableImage.h"

// Construct with edge modes.
BilinearInterpolator::BilinearInterpolator(EdgeMode horizontal_edge,
                                           EdgeMode vertical_edge)
    : TiledInterpolator(horizontal_edge, vertical_edge) {}

BilinearInterpolator::~BilinearInterpolator() {}

// Returns color of nearest pixel.
Color BilinearInterpolator::pixel(const ReadableImage& image, double i,
    double j) const {
  // Get surrounding pixels.
  Color top_left = access(image, floor(i), floor(j));
  Color top_right = access(image, floor(i), ceil(j));
  Color bottom_left = access(image, ceil(i), floor(j));
  Color bottom_right = access(image, ceil(i), ceil(j));

  // Calculate position within interpolating square.
  double v = i - floor(i);
  double h = j - floor(j);

  // Interpolate across horizontal edges.
  Color top = (1 - h) * top_left + h * top_right;
  Color bottom = (1 - h) * bottom_left + h * bottom_right;

  return (1 - v) * top + v * bottom;
}

